<?php defined('IN_NWIDC') or exit('Access Invalid!');?>
<!-- <script src='/layer'></script> -->
<div class="page">
  <div class="fixed-bar">
    <div class="item-title">
      <h3>微信接口设置</h3>
      <ul class="tab-base">
        <li><a href="JavaScript:void(0);" class="current"><span>自定义菜单</span></a></li>
        <li><a href="index.php?act=wechat&op=reply" ><span>回复设置</span></a></li>
        <li><a href="index.php?act=wechat&op=config" ><span>接口设置</span></a></li>
      </ul>
    </div>
  </div>
  <div class="fixed-empty"></div>

  <table class="table tb-type2" id="prompt">
    <tbody>
      <tr class="space odd">
        <th colspan="12"><div class="title">
            <h5><?php echo $lang['nc_prompts'];?></h5>
            <span class="arrow"></span></div></th>
      </tr>
      <tr>
        <td><ul>
            <li>
              如果一个菜单是末级菜单，那么它必须有一个合法的链接（不能随便填）
            </li>
            <li>
              如果一个菜单还有子菜单，那么它一定不能有链接，否则会出错
            </li>
          </ul></td>
      </tr>
    </tbody>
  </table>   
  <form method="post" id='form_list' action="index.php?act=admin_log&op=list_del">
    <input type="hidden" name="form_submit" value="ok" />
    <div style="text-align:right;">
      <a class="btns" href="javascript:void(0);" id="new_item"><span>添加新菜单</span></a>
    </div>
    <table class="table tb-type2">
      <thead>
        <tr class="thead">
          <th>菜单名</th>
          <th>行为</th>
          <th>链接</th>
          <th>操作</th>
        </tr>

        <script type='tpl'>
          <tr class='first_menu'>
            <td>
              <div class='issub'></div>
              <input type="text" name='name'>
            </td>
            <td>
              <select name="" id="">
                <option value="">链接</option>
              </select>
            </td>
            <td>
              <input type="text" name='url' value=''>
            </td>
            <td>
              <a href="javascript:;" class='add_sub'>添加下级菜单</a>
              <a href="javascript::" class='del'>删除</a>
            </td>
          </tr>
        </script>
      </thead>

      <?php
        require_wechat();
        $wechat = new WeChat(-1);
        $menu_list = $wechat->get_menu_list();

 //        $ret = $wechat->set_menu_list(json_decode('{
 //     "button":[
 //     {  
 //          "type":"click",
 //          "name":"今日歌曲",
 //          "key":"V1001_TODAY_MUSIC"
 //      },
 //      {
 //           "name":"菜单",
 //           "sub_button":[
 //           {  
 //               "type":"view",
 //               "name":"搜索",
 //               "url":"http://www.soso.com/"
 //            },
 //            {
 //               "type":"view",
 //               "name":"视频",
 //               "url":"http://v.qq.com/"
 //            },
 //            {
 //               "type":"click",
 //               "name":"赞一下我们",
 //               "key":"V1001_GOOD"
 //            }]
 //       }]
 // }',true));

        // print_r($ret);

        
        // print_r($wechat->get_menu_list())
      ?>
      <script>
        var menu_list = <?php echo json_encode($menu_list); ?>;

        function make_item(data,is_submenu){
            var item = $(tpl);
            item.find('[name=name]').val(data.name);
            item.find('[name=url]').val(data.url);
            if(is_submenu){
                item.addClass('submenu').removeClass('first_menu');
            }
            box.append(item);
        }
        menu_list = menu_list.menu.button;
        $(function(){
          console.log(menu_list);
          for(var i in menu_list){
              make_item(menu_list[i]);
              
              if(menu_list[i].sub_button){
                  var buttons = menu_list[i].sub_button;
                  for(var j in buttons){
                      make_item(buttons[j],true);
                  }
              }

          }
        })
      </script>
      <style>
        .submenu .issub{
            width: 25px;
            height: 15px;
            display: inline-block;
            *display: inline;
            margin-left: 10px;
            border-left: 1px solid #000;
            border-bottom: 1px solid #000;
        }

        .submenu .add_sub{
          display: none;
        }
      </style>
      <tbody class='tbody'>
        

      </tbody>

      <tfoot>
        <tr>
          <td  colspan='20'>
            <a href="javascript:;" id='save' class='btn'>保存设置</a>
          </td>
        </tr>
      </tfoot>

      <script>
        var layer = parent.layer;
        var tpl = $('[type=tpl]').html();

        var box = $('.tbody');

        function get_sub_menu(tr,return_last){
            var ret = [];
            //如果没有下一个
            if(!tr.next().length){
                return return_last ? tr : ret;
            }
            var next = tr.next();
            while(next.length){
                //碰到下一个的时候
                if(next.hasClass('first_menu')){
                    return return_last ? ret.pop() : ret;
                }
                ret.push(next);
                next = next.next();
            }

            return return_last ? ret.pop() || _this : ret;
        }

        $('#new_item').click(function(){
            var newitem = $(tpl);
            if(box.find('tr.first_menu').length > 2){
              layer.msg('最多只能有三个一级菜单！');
              return;
            }
            $('.tbody').append(newitem);
        });

        box.on('click','.add_sub',function(){
          var _this = $(this).closest('tr');
          var newitem = $(tpl).addClass('submenu').removeClass('first_menu');
          var last = get_sub_menu(_this,true);
          newitem.insertAfter(last);
        })

        box.on('click','.del',function(){
          var _this = $(this).closest('tr');
          var submenu = get_sub_menu(_this);
          _this.remove();
          $(submenu).each(function(){$(this).remove()})
        });

        $('#save').click(function(){
            var data = {button : []};
            var flag = 0;
            $('tr.first_menu').each(function(){
                var _this = $(this);
                var submenu = get_sub_menu(_this);

                //一个菜单没有子菜单时，必须有一个合法链接
                if(!submenu.length){
                    if($.trim(_this.find('[name=url]').val()) == ''){
                        layer.msg('请检查您的设置，当一个菜单没有子菜单时，必须有一个合法的链接');
                        flag++;
                        return;
                    }
                }

                var obj = {}

                if(_this.find('[name=url]').val() != ''){
                    obj.type = 'view';
                    obj.url = _this.find('[name=url]').val()
                }

                obj.name = _this.find('[name=name]').val();

                if(submenu.length){
                  obj.sub_button = [];
                  for(var i = 0; i < submenu.length; i++){
                      if(submenu[i].find('[name=url]').val() == ''){
                          layer.msg('请给' + submenu[i].find('[name=name]').val() + '一个合法的链接！');
                          flag++;
                      }
                      obj.sub_button.push({
                        type : 'view',
                        name : submenu[i].find('[name=name]').val(),
                        url : submenu[i].find('[name=url]').val()
                      });
                  }
                }
                data.button.push(obj);
            });

            if(flag){
              return;
            }

            var json = JSON.stringify(data);

            console.log(json);

            var index = layer.load();
            $.post('index.php?act=wechat&op=update_custom',{json:json},function(msg){
              console.log(msg);
                layer.close(index);
                if(msg == 'success'){
                  layer.msg('保存成功',{icon:1});
                }
                else{
                  layer.msg('保存失败',{icon:2});
                }
            });
        });

      </script>

    </table>
  </form>
</div>
<script type="text/javascript" src="<?php echo RESOURCE_SITE_URL;?>/js/jquery-ui/jquery.ui.js"></script> 
<script type="text/javascript" src="<?php echo RESOURCE_SITE_URL;?>/js/jquery-ui/i18n/zh-CN.js" charset="utf-8"></script>
<link rel="stylesheet" type="text/css" href="<?php echo RESOURCE_SITE_URL;?>/js/jquery-ui/themes/ui-lightness/jquery.ui.css"  />
<script type="text/javascript">
$(function(){
    $('#time_from').datepicker({dateFormat: 'yy-mm-dd'});
    $('#time_to').datepicker({dateFormat: 'yy-mm-dd'});
    $('#ncexport').click(function(){
    	$('input[name="op"]').val('export_step1');
    	$('#formSearch').submit();
    });
    $('#ncsubmit').click(function(){
    	$('input[name="op"]').val('list');
    	$('#formSearch').submit();
    });
    $('#ncdelete').click(function(){
        $('#delago').val($('#delago1').val());
    	$('input[name="op"]').val('list_del');$('#formSearch').submit();
    });
});
</script>
